import Vue from "vue";
import appConfig from "../config/appConfig";

const socket = new WebSocket(appConfig.onLineWebsocket + '/pkgame');

Vue.prototype.socket = socket;

socket.onopen = function (msg) {
    console.log(msg)
}

socket.onclose = function (e) {
    console.log('连接断开' + e.code + ' ' + e.reason + ' ' + e.wasClean);
    location.href = appConfig.onLineApiDomain + '/index';
}

socket.onerror = function () {
    console.log('连接错误');
    location.href = appConfig.onLineApiDomain + '/index';
}

socket.sendMessage = function(msg){
    // Wait until the state of the socket is not ready and send the message when it is...
    waitForSocketConnection(socket, function(){
        console.log("message sent!!!");
        socket.send(JSON.stringify(msg));
    });
}

// Make the function wait until the connection is made...
function waitForSocketConnection(socket, callback){
    setTimeout(
        function () {
            if (socket.readyState === 1) {
                console.log("Connection is made")
                if (callback != null){
                    callback();
                }
            } else {
                console.log("wait for connection...")
                waitForSocketConnection(socket, callback);
            }

        }, 5); // wait 5 millisecond for the connection...
}

export {socket};
